<template>
  <div class="chart-container" v-loading="loading" element-loading-text="过程线加载中，请稍后">
    <!-- 空状态提示 -->
    <div v-if="chartDataList.length === 0 && !loading" class="empty-state">
      <noData showChart description="暂无过程线数据，请先添加过程线"/>
    </div>

    <!-- 图表卡片列表 -->
    <div class="chart-cards" v-if="chartDataList.length > 0">
      <div 
        v-for="(item, index) in chartDataList" 
        :key="`chart-${item.id}-${index}`" 
        class="chart-card"
        :class="{ 'chart-card-expanded': expandedChartIds.includes(item.id) }"
      >
        <!-- 卡片头部 -->
        <div class="chart-card-header" @click="toggleChart(item.id)">
          <div class="chart-title">
            <i class="el-icon-s-data title-icon"></i>
            <span class="title-text">{{ item.data.line.name }}</span>
          </div>
          
          <div class="chart-actions">
            <el-tooltip effect="dark" content="展开/折叠图表" placement="top">
              <i 
                class="el-icon-arrow-down expand-icon" 
                :class="{ 'expanded': expandedChartIds.includes(item.id) }"
              ></i>
            </el-tooltip>
          </div>
        </div>
        
        <!-- 图表内容 -->
        <transition name="el-zoom-in-top">
          <div v-show="expandedChartIds.includes(item.id)" class="chart-card-content">
            <!-- 图表操作栏 -->
            <div class="chart-toolbar">
              <el-tooltip class="item" effect="dark" content="修改过程线" placement="top">
                <el-button 
                  size="mini" 
                  icon="el-icon-edit" 
                  @click="handleAddLine(item.data.line)"
                  class="toolbar-btn"
                  type="primary"
                >修改</el-button>
              </el-tooltip>
              
              <el-tooltip class="item" effect="dark" content="配置过程线" placement="top">
                <el-button 
                  size="mini" 
                  icon="el-icon-setting" 
                  @click="handleSetLineDataDialog(item.data.line.id, item.data.lineInfos)"
                  class="toolbar-btn"
                  type="primary"
                >配置</el-button>
              </el-tooltip>
              
              <el-tooltip class="item" effect="dark" content="删除过程线" placement="top">
                <el-button 
                  size="mini" 
                  icon="el-icon-delete" 
                  @click="handleDelLine(item.data.line.id, item.data.line.name)"
                  class="toolbar-btn"
                  type="danger"
                >删除</el-button>
              </el-tooltip>
              
              <el-divider direction="vertical" v-if="!isSetting"></el-divider>
              
              <el-tooltip class="item" effect="dark" content="恢复删除点" placement="top" v-if="!isSetting">
                <el-button 
                  size="mini" 
                  icon="el-icon-refresh" 
                  @click="handlerestoreLine(item.data.line.id, index)"
                  class="toolbar-btn"
                >恢复点</el-button>
              </el-tooltip>
              
              <el-tooltip class="item" effect="dark" content="数据过滤" placement="top" v-if="!isSetting">
                <el-button 
                  size="mini" 
                  icon="el-icon-finished" 
                  @click="handleSetFilterData(item.data.lineInfos)"
                  class="toolbar-btn"
                >数据过滤</el-button>
              </el-tooltip>
              
              <el-tooltip class="item" effect="dark" content="审核状态筛选" placement="top" v-if="!isSetting">
                <el-button 
                  size="mini" 
                  icon="el-icon-document-checked" 
                  @click="handleSetExamineData(item.data.line)"
                  class="toolbar-btn"
                >审核状态</el-button>
              </el-tooltip>
              
              <el-tooltip class="item" effect="dark" content="时间设置" placement="top" v-if="!isSetting">
                <el-button 
                  size="mini" 
                  icon="el-icon-time" 
                  @click="handleSetTimeData(item.data.lineInfos[0])"
                  class="toolbar-btn"
                >时间设置</el-button>
              </el-tooltip>
            </div>
            
            <!-- 图表容器 -->
            <div 
              class="chart-wrapper" 
              :style="{
                width: item.data.line.width ? item.data.line.width + 'px' : '100%', 
                height: item.data.line.height ? item.data.line.height + 'px' : '340px'
               
              }"
               v-loading="chartLoading[item.id]"
                element-loading-text="图表更新中"
                element-loading-background="rgba(255, 255, 255, 0.8)"
            >
              <div 
                :id="`chart${item.id}`" 
                class="chart-line" 
                :ref="`chart${item.id}`"
                :style="{
                width: item.data.line.width ? item.data.line.width + 'px' : '100%', 
                height: item.data.line.height ? item.data.line.height + 'px' : '340px'
               
              }"
              ></div>
            </div>
            
            <!-- 图表信息栏 -->
            <div class="chart-info">
              <div class="info-item">
                <span class="info-label">数据点数:</span>
                <span class="info-value">{{ getDataPointCount(item.data) }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">时间范围:</span>
                <span class="info-value">{{ getTimeRange(item.data) }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">审核状态:</span>
                <span class="info-value">{{ getSatusShow(item.data) }}</span>
              </div>
            </div>
          </div>
        </transition>
      </div>
    </div>

    <!-- 添加/编辑过程线对话框 -->
    <infoDialog 
      :visible.sync="linesAddDialog" 
      :linesDialogForm="linesDialogForm" 
      @saveLineDialog="handleSaveLineDialog" 
      name="过程线"
    />

    <!-- 配置过程线对话框 -->
    <setLineData 
      :visible.sync="setLineDataDialog" 
      name="过程线" 
      :stationId="stationId" 
      :setDataForm="setDataForm" 
      :lineId="LineID"
      @saveSetDialog="handleSaveSetDialog" 
      :isSetting="isSetting"
    />

    <!-- 恢复删除点对话框 -->
    <refreshDelPoint 
      :visible.sync="restoreVisible" 
      :restoreList="restoreList" 
      @closeRefreshDel="handleCloseRefreshDel"
    />

    <!-- 数据过滤对话框 -->
    <filterDialog 
      :visible.sync="filterVisible" 
      :filterSelectList="filterSelectList" 
      :lineID="LineID"
    />

    <!-- 审核状态对话框 -->
    <el-dialog
        title="审核状态设置" 
        v-dialogDrag 
        :visible.sync="examineDialogVisible" 
        width="420px"
        :close-on-click-modal="false"
        class="examine-filter-dialog"
    >
        <div class="dialog-content">
            <!-- 筛选说明 -->
            <div class="filter-tip">
            <i class="el-icon-filter"></i>
            <span>选择要显示的审核状态数据</span>
            </div>

            <!-- 状态筛选 -->
            <div class="filter-section">
            <div class="filter-header">
                <span class="filter-title">审核状态</span>
                <div class="quick-actions">
                <el-button size="mini" text @click="selectAll">全选</el-button>
                <el-divider direction="vertical"></el-divider>
                <el-button size="mini" text @click="clearAll">清空</el-button>
                </div>
            </div>

            <el-checkbox-group v-model="OUTLIERSIGNs" class="compact-checkbox-group">
                <div class="compact-option">
                <el-checkbox :label="0" class="compact-checkbox">
                    <div class="option-content">
                    <span class="status-badge pending"></span>
                    <span class="status-text">未审核</span>
                    </div>
                </el-checkbox>
                </div>

                <div class="compact-option">
                <el-checkbox :label="1" class="compact-checkbox">
                    <div class="option-content">
                    <span class="status-badge approved"></span>
                    <span class="status-text">审核通过</span>
                    </div>
                </el-checkbox>
                </div>

                <div class="compact-option">
                <el-checkbox :label="2" class="compact-checkbox">
                    <div class="option-content">
                    <span class="status-badge rejected"></span>
                    <span class="status-text">审核未通过</span>
                    </div>
                </el-checkbox>
                </div>
            </el-checkbox-group>
            </div>

            <!-- 筛选统计 -->
            <div class="filter-stats">
            <div class="stats-item">
                <span class="stats-label">已选择:</span>
                <span class="stats-value">{{ OUTLIERSIGNs.length }}/3 个状态</span>
            </div>
            </div>
        </div>

        <div class="dialog-footer">
            <el-button @click="examineDialogVisible = false" size="small" icon="el-icon-circle-close" class="cancel-btn">取消</el-button>
            <el-button 
            type="primary" 
            @click="handleConfirmExamine" 
            size="small"
            class="confirm-btn"
            icon="el-icon-upload"
            >
            保存配置
            </el-button>
        </div>
    </el-dialog>

    <el-dialog
        title="时间范围设置" 
        v-dialogDrag 
        :visible.sync="timeDialogVisible" 
        width="500px"
        :close-on-click-modal="false"
        >
      <div class="dialog-content">
        <!-- 时间类型选择 -->
        <div class="setting-section">
          <div class="section-header">
            <i class="el-icon-time"></i>
            <span class="section-title">时间类型</span>
          </div>
          <div class="type-radio-group">
            <div :class="timeData.DtModeID == 3 ? 'type-radio is-checked' : 'type-radio'">
              <div class="radio-content" @click="changeTimeType(3)">
                <i class="el-icon-date"></i>
                <div>
                    <p class="radio-text">时间段</p>
                    <p class="radio-desc">选择开始和结束日期</p>
                </div>
              </div>
            </div>
            <div :class="timeData.DtModeID == 4 ? 'type-radio is-checked' : 'type-radio'">
              <div class="radio-content" @click="changeTimeType(4)">
                <i class="el-icon-timer"></i>
                <div>
                    <p class="radio-text">截止时间</p>
                    <p class="radio-desc">选择单个截止日期</p>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 日期设置 -->
        <div class="setting-section">
          <div class="section-header">
            <i class="el-icon-setting"></i>
            <span class="section-title">日期设置</span>
          </div>
          
          <!-- 截止时间模式 -->
          <div v-if="timeData.DtModeID == 4" class="date-setting">
            <div class="date-label">
              <i class="el-icon-arrow-right"></i>
              <span>截止日期</span>
            </div>
            <el-date-picker
              v-model="timeData.dT1"
              type="date"
              size="small"
              format="yyyy年MM月dd日"
              value-format="yyyy/MM/dd"
              placeholder="选择截止日期"
              class="compact-date-picker"
            >
            </el-date-picker>
          </div>

          <!-- 时间段模式 -->
          <div v-if="timeData.DtModeID == 3" class="date-setting">
            <div class="date-range-group">
              <div class="date-item">
                <div class="date-label">
                  <i class="el-icon-caret-right"></i>
                  <span>开始日期</span>
                </div>
                <el-date-picker
                  v-model="timeData.dT1"
                  type="date"
                  size="small"
                  format="yyyy年MM月dd日"
                  value-format="yyyy/MM/dd"
                  placeholder="开始日期"
                  class="compact-date-picker"
                >
                </el-date-picker>
              </div>
              <div class="date-item">
                <div class="date-label">
                  <i class="el-icon-caret-left"></i>
                  <span>结束日期</span>
                </div>
                <el-date-picker
                  v-model="timeData.dT2"
                  type="date"
                  size="small"
                  format="yyyy年MM月dd日"
                  value-format="yyyy/MM/dd"
                  placeholder="结束日期"
                  class="compact-date-picker"
                >
                </el-date-picker>
              </div>
            </div>
            <!-- 时间段验证 -->
            <div v-if="showDateWarning" class="date-warning">
              <i class="el-icon-warning"></i>
              <span>结束日期不能早于开始日期</span>
            </div>
          </div>
        </div>

        <!-- 快捷操作 -->
        <div class="setting-section">
            <div class="section-header">
                <i class="el-icon-position"></i>
                <span class="section-title">快捷操作</span>
            </div>
            <div>
                <el-button size="mini" @click="setQuickDate('today')">今天</el-button>
                <el-button size="mini" @click="setQuickDate('yesterday')">昨天</el-button>
                <el-button size="mini" @click="setQuickDate('week')">本周</el-button>
                <el-button size="mini" @click="setQuickDate('month')">本月</el-button>
                <el-button size="mini" @click="setQuickDate('7days')">最近7天</el-button>
                <el-button size="mini" @click="setQuickDate('15days')">最近15天</el-button>
            </div>
        </div>
      </div>

      <div  class="dialog-footer">
        <el-button @click="timeDialogVisible = false" size="small" class="cancel-btn" icon="el-icon-circle-close">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleConfirmTime" 
          size="small"
          :disabled="!isFormValid"
          class="confirm-btn"
          icon="el-icon-upload"
        >
          保存配置
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getLineViewsByTreeID,linesDel,getLineInfosV1,delDataOnLine,setLineOUTLIERSIGN,LineInfoTime} from "@/api/https";
import infoDialog from './infoDialog.vue'
import setLineData from './setLineDialog.vue'
import refreshDelPoint from './refreshDelPoint.vue'
import filterDialog from './filterChart.vue'
import noData from '@/components/base/noData.vue'
export default ({
  components: {infoDialog, setLineData, refreshDelPoint, filterDialog, noData},
  props: {
    stationId: {
      type: [String, Number],
      default: ''
    },
    treeId: {
      type: Number,
      default: 0
    },
    isReload: {
      type: Boolean,
      default: false
    },
    isSetting: {
      type: Boolean,
      default: false
    }
  },
  mounted() {
    this.debouncedLoad(true);
    window.addEventListener('resize', this.handleResize);
  },
  data() {
    return {
      loading: false,
      chartDataList: [],
      expandedChartIds: [],
      chartInstances: {},
      linesDialogForm: {},
      setLineDataDialog: false,
      LineID: 0,
      linesAddDialog: false,
      setDataForm: [],
      resizeTimer: null,
      restoreVisible: false,
      restoreList: [],
      filterVisible: false,
      filterSelectList: [],
      examineDialogVisible: false,
      OUTLIERSIGNs: [],
      timeDialogVisible: false,
      timeData: {},
      startTime: '',
      endTime: '',
      chartLoading: {},
      requestTimer:null
    }
  },
  deactivated() {
    this.debouncedLoad();
  },
  beforeDestroy() {
    this.debouncedLoad();
    this.isLoad = false
    window.removeEventListener('resize', this.handleResize);
  },
  watch: {
    stationId: {
      handler(newVal, oldVal) {
        if(newVal){
          this.debouncedLoad(true);
        }
      },
    },
    treeId: {
      handler(newVal, oldVal) {
        this.debouncedLoad(true);
      },
      immediate: false,
    },
    
    isReload: {
      handler(newVal, oldVal) {
        if (newVal) {
          this.debouncedLoad(true);
          this.$emit('update:isReload', false);
        }
      },
      immediate: true,
    },
  },
  computed: {
    // 表单验证
    isFormValid() {
      if (this.timeData.DtModeID === 4) {
        return !!this.timeData.dT1;
      } else if (this.timeData.DtModeID === 3) {
        return !!this.timeData.dT1 && !!this.timeData.dT2 && !this.showDateWarning;
      }
      return false;
    },
    
    // 日期范围验证
    showDateWarning() {
      if (this.timeData.DtModeID === 3 && this.timeData.dT1 && this.timeData.dT2) {
        return new Date(this.timeData.dT1) > new Date(this.timeData.dT2);
      }
      return false;
    },

  },
  methods: {    
    getDataPointCount(data) {
      if (!data.lineData1) return 0;
      return data.lineData1.reduce((total, item) => total + (item.valueData ? item.valueData.length : 0), 0);
    },
    
    getTimeRange(data) {
      if (!data.lineData1 || data.lineData1.length === 0) return '无数据';
      
      const firstItem = data.lineData1[0];
      const lastItem = data.lineData1[data.lineData1.length - 1];
      
      if (!firstItem.valueData || firstItem.valueData.length === 0) return '无数据';
      
      const startTime = firstItem.valueData[0].watchTime;
      const endTime = firstItem.valueData[firstItem.valueData.length - 1].watchTime;
      
      return `${startTime.split(' ')[0]} 至 ${endTime.split(' ')[0]}`;
    },
    getSatusShow(data){
        if(!data.line || !data.line.OUTLIERSIGNs || data.line.OUTLIERSIGNs.length <= 0){
            return '暂无'
        }

        const sta = []
        data.line.OUTLIERSIGNs.forEach(item=>{
            if(item == 0){
                sta.push('未审核')
            }

            if(item == 1){
                sta.push('审核通过')
            }

            if(item == 2){
                sta.push('审核未通过')
            }
        })

        return sta.join(',')
    },
    toggleChart(chartId) {
      const index = this.expandedChartIds.indexOf(chartId);
      if (index > -1) {
        this.expandedChartIds.splice(index, 1);
      } else {
        this.expandedChartIds.push(chartId);
        this.$nextTick(() => {
          this.redrawChart(chartId);
        });
      }
    },
    
    handleResize() {
      if (this.resizeTimer) clearTimeout(this.resizeTimer);
      this.resizeTimer = setTimeout(() => {
        Object.keys(this.chartInstances).forEach(id => {
          const instance = this.chartInstances[id];
          if (instance && !instance.isDisposed()) {
            instance.resize();
          }
        });
      }, 300);
    },
    
    handleSetExamineData(data) {
      this.OUTLIERSIGNs = data.OUTLIERSIGNs || [];
      this.LineID = data.id;
      this.examineDialogVisible = true;
    },
    
    handleConfirmExamine() {
      if (this.OUTLIERSIGNs.length === 0) {
        this.$message.warning('请至少选择一个审核状态');
        return;
      }
      
      setLineOUTLIERSIGN({
        lineID: this.LineID,
        outliersigNs: this.OUTLIERSIGNs
      }).then(res => {
        if (res.isSuccess) {
          this.onGetLineInfo(() => {
            this.examineDialogVisible = false;
            this.OUTLIERSIGNs = [];
            this.LineID = 0;
            this.$message.success('审核状态设置成功');
          });
        } else {
          this.$message.error(res.errorMessage);
        }
      });
    },
    
    handleSetTimeData(data) {
      this.timeData = {...data};
      this.LineID = data.lineID;
      this.timeDialogVisible = true;
      this.startTime = data.dT1;
      this.endTime = data.dT2;
    },
    
    handleConfirmTime() {
      if (this.timeData.DtModeID === 3 && (!this.timeData.dT1 || !this.timeData.dT2)) {
        this.$message.warning('请选择完整的时间段');
        return;
      }
      
      if (this.timeData.DtModeID === 4 && !this.timeData.dT1) {
        this.$message.warning('请选择截止时间');
        return;
      }
      
      LineInfoTime({
        lineID: this.LineID,
        dtModeID: this.timeData.DtModeID,
        b_Time: this.timeData.dT1,
        e_Time: this.timeData.dT2,
      }).then(res => {
        if (res.isSuccess) {
          this.onGetLineInfo(() => {
            this.timeDialogVisible = false;
            this.timeData = {};
            this.LineID = 0;
            this.$message.success('时间设置成功');
          });
        } else {
          this.$message.error(res.errorMessage);
        }
      });
    },
    
    onGetLineInfo(callback) {
      this.$set(this.chartLoading, this.LineID, true);
      getLineInfosV1({
        b_Time: this.startTime || '',
        e_Time: this.endTime || '',
        lineID: this.LineID
      }).then(res => {
        if (res.isSuccess) {
          this.chartDataList.forEach(item => {
            if (item.id == this.LineID) {
              item.data = {...res.data};
              this.redrawChart(this.LineID);
            }
          });
        }
      }).finally(() => {
        this.$set(this.chartLoading, this.LineID, false);
        this.startTime = '';
        this.endTime = '';
        this.LineID = 0;
        if (typeof callback === 'function') {
          callback();
        }
      });
    },
    
    clearChart(isReload) {
      if (this.resizeTimer) {
        clearTimeout(this.resizeTimer);
        this.resizeTimer = null;
      }
      Object.keys(this.chartInstances).forEach(id => {
        const instance = this.chartInstances[id];
        if (instance && !instance.isDisposed()) {
          instance.off('click');
          instance.dispose();
        }
        delete this.chartInstances[id];
      });
      this.chartInstances = {};
      
      if (isReload) {
        this.$nextTick(() => {
          this.handleGetLineViewsByTreeID();
        });
      }
    },

    debouncedLoad(isReload) {
      if (this.requestTimer) clearTimeout(this.requestTimer);
      this.requestTimer = setTimeout(() => {
        this.clearChart(isReload);
      }, 50);
    },
    
    redrawChart(chartId) {
      const chartData = this.chartDataList.find(item => item.id === chartId)?.data;
      if (!chartData) {
        this.$set(this.chartLoading, chartId, false);
        return;
      }

      if ((!chartData.lineData1 || chartData.lineData1.length === 0) && 
      (!chartData.lineData2 || chartData.lineData2.length === 0)) {
    
        // 清空图表
        if (this.chartInstances[chartId] && !this.chartInstances[chartId].isDisposed()) {
          this.chartInstances[chartId].clear();
          this.chartInstances[chartId].setOption({
            title: {
              text: '暂无数据',
              left: 'center',
              top: 'center',
              textStyle: {
                color: '#999',
                fontSize: 14
              }
            }
          }, true);
        }
        
    
        return;
      }


      if (!this.chartInstances[chartId] || this.chartInstances[chartId].isDisposed()) {
        const dom = document.getElementById(`chart${chartId}`);
        if (!dom) return;
        this.chartInstances[chartId] = this.$echarts.init(dom);
      }

      const chartInstance = this.chartInstances[chartId];
      this.drawLinchart(chartData, chartInstance);

      if (this.resizeTimer) clearTimeout(this.resizeTimer);
      this.resizeTimer = setTimeout(() => {
        if (!chartInstance.isDisposed()) {
          chartInstance.resize();
        }
      }, 200);
    },
    
    handleGetLineViewsByTreeID() {
      if (this.treeId && this.treeId == 0) {
        this.debouncedLoad(false);

        return;
      }
      this.loading = true;
      this.chartDataList = [];
      this.expandedChartIds = [];
      getLineViewsByTreeID({
        GraphTreeID: this.treeId,
        StationID: this.stationId
      }).then(res => {
        if (res.isSuccess) {
          if (res.data.length > 0) {
            res.data.forEach((item, index) => {
              this.chartDataList.push({
                id: item.line.id,
                name: item.line.name,
                data: item
              });
              this.expandedChartIds.push(item.line.id);
            });
            this.$nextTick(() => {
              this.initChart();
            });
            this.loading = false;
          } else {
            this.loading = false;
          }
        } else {
          this.loading = false;
        }
      }).finally(() => {
        this.loading = false;
      });
    },
    
    initChart() {
      this.chartDataList.forEach((item, index) => {
        const dom = document.getElementById(`chart${item.id}`);
        if (!dom) return;

        // 销毁旧实例（如果存在）
        if (this.chartInstances[item.id] && !this.chartInstances[item.id].isDisposed()) {
          this.chartInstances[item.id].dispose();
        }

        // 创建新实例
        const chart = this.$echarts.init(dom);
        this.chartInstances[item.id] = chart;
        this.drawLinchart(item.data, chart);
      });
    },
    
    getSymbolType(icon) {
      const symbols = [
        'circle', 'emptyCircle', 'rectangle', 'emptyRectangle',
        'triangle', 'emptyTriangle', 'diamond', 'emptyDiamond'
      ];
      return symbols[icon - 1] || 'emptyCircle';
    },
    
    formatTime(value, format, part) {
      const formats = {
        1: {1: 'yyyy年MM月dd日', 2: 'yyyy年MM月', 3: 'yyyy年'},
        2: {1: 'yyyy/MM/dd', 2: 'yyyy/MM', 3: 'yyyy'},
        3: {1: 'yyyy-MM-dd', 2: 'yyyy-MM', 3: 'yyyy'}
      };
      return this.$echarts.format.formatTime(formats[format]?.[part] || 'yyyy-MM-dd', value);
    },
    
    generateSeriesData(lineData, yAxisIndex = 0) {
      return lineData.map(itemData => ({
        name: itemData.point,
        type: 'line',
        data: itemData.valueData.map(sub => sub.value === null ? null : Number(sub.value)),
        connectNulls: true,
        showAllSymbol: true,
        yAxisIndex,
        showSymbol: itemData.icon && Number(itemData.icon) > 0,
        symbol: this.getSymbolType(itemData.icon),
        symbolSize: 5,
        itemStyle: {color: itemData.color},
        lineStyle: {color: itemData.color, width: itemData.blod}
      }));
    },
    
    getUnitText(chartData, lineData, unitTxtKey, defaultPrefix = '单位') {
      const unit = lineData[0]?.unit;
      return unit ? (chartData.line[unitTxtKey] || `${defaultPrefix}(${unit})`) : null;
    },
    
    drawLinchart(chartData, chartInstance) {
      chartInstance.off('click');
      if (!chartInstance || chartInstance.isDisposed()) return;

      const {lineData1, lineData2, line} = chartData;

      if ((!lineData1 || lineData1.length === 0) && 
      (!lineData2 || lineData2.length === 0)) {
    
        chartInstance.clear();
        chartInstance.setOption({
          title: {
            text: '暂无数据',
            left: 'center',
            top: 'center',
            textStyle: {
              color: '#999',
              fontSize: 14
            }
          }
        }, true);
        return;
      }

      const LineKeys = lineData1?.[0]?.valueData?.map(sub => sub.watchTime.split(' ')[0]) || [];
      const nameList = [
        ...(lineData1?.map(item => item.point) || []),
        ...(lineData2?.map(item => item.point) || [])
      ];

      const series = [
        ...(lineData1 ? this.generateSeriesData(lineData1) : []),
        ...(lineData2 ? this.generateSeriesData(lineData2, 1) : [])
      ];

      const yAxis = [];
      if (lineData1?.length) {
        yAxis.push({
          type: 'value',
          interval: Number(line.valueLen),
          max: line.valueMax,
          min: line.valueMin,
          name: this.getUnitText(chartData, lineData1, 'unitTxt'),
          axisLine: {show: true},
          splitLine: {show: true, lineStyle: {type: 'dashed', color: '#a8a8a8'}},
          axisLabel: {formatter: value => value.toString()}
        });
      }
      if (lineData2?.length) {
        yAxis.push({
          type: 'value',
          scale: true,
          interval: Number(line.valueLen1),
          max: line.valueMax1,
          min: line.valueMin1,
          name: this.getUnitText(chartData, lineData2, 'unitTxt1'),
          axisLine: {show: true},
          splitLine: {show: true, lineStyle: {type: 'dashed', color: '#a8a8a8'}},
          axisLabel: {formatter: value => value.toString()}
        });
      }

      const option = {
          tooltip: { trigger: 'axis', confine: true },
          legend: { top: "20", data: nameList, type: 'scroll' },
          grid: {
          top: 70,
          left: '5%',
          right: '5%',
          bottom: 40,
          containLabel: true,
          borderWidth: 1,
          show: true,
          borderColor: '#000'
          },
          toolbox: {
          feature: {
              dataZoom: { yAxisIndex: 'none' },
              saveAsImage: {}
          }
          },
          xAxis: {
          type: 'category',
          axisLabel: {
              interval: Number(line.t_Len),
              formatter: value => this.formatTime(value, line.t_Format, line.t_Part)
          },
          name: '日期',
          nameLocation: 'middle',
          data: LineKeys,
          nameTextStyle: { 
              padding: [0, 0, 0, line.width ? line.width - 70 : 850] 
          },
          onZero: false,
          boundaryGap: ['2%', '2%'],
          axisLine: { onZero: false },
          splitLine: {
              show: true,
              lineStyle: { type: 'dashed', color: '#a8a8a8' }
          }
          },
          yAxis,
          dataZoom: [{ type: 'inside' }],
          series
      };
      chartInstance.setOption(option, true);

      // 图表点击事件（删除数据点）
      chartInstance.on('click', params => {
        this.$confirm(`确认删除${params.seriesName}线上的点？ 时间：${params.name}，值：${params.value}`,'提示', {
          type: 'warning',
          confirmButtonText: '确认删除',
          cancelButtonText: '取消'
        }).then(() => {
          const name = params.seriesName;
          const _data = chartData.lineInfos.filter(item => {
            return item.pointName == name
          });
          delDataOnLine({
            ID: _data[0].id,
            codeID: _data[0].codeID,
            WATCHTIME: params.name,
            lineID: _data[0].lineID,
            val: params.value
          }).then(res => {
            if (res.isSuccess) {
              this.onGetLineInfo(() => {
                this.$message.success('数据点删除成功');
              });
            } else {
              this.$message.error(res.errorMessage);
            }
          });
        }).catch(() => {
        });
      });
    },
    
    handleAddLine(data) {
      this.linesAddDialog = true;
      this.linesDialogForm = {...data};
    },
    
    handleSaveLineDialog(data) {
      this.LineID = data.id;
      this.onGetLineInfo(() => {
        this.linesDialogForm = {};
        this.$message.success('过程线修改成功');
      });
    },
    
    handleSetLineDataDialog(id, info) {
      this.LineID = id;
      this.setDataForm = [...info];
      this.setLineDataDialog = true;
    },
    
    handleSaveSetDialog(data) {
      this.LineID = data[0].lineID;
      this.onGetLineInfo(() => {
        this.setDataForm = [];
        this.$message.success('过程线配置成功');
      });
    },
    
    handleDelLine(id, name) {
      this.$confirm(`确认删除名称为 ${name} 的过程线？`,'提示', {
        type: 'warning',
      }).then(() => {
        linesDel({ID: id}).then(res => {
          if (res.isSuccess) {
            if (this.chartInstances[id]) {
              this.chartInstances[id].dispose();
              delete this.chartInstances[id];
            }
            this.chartDataList = this.chartDataList.filter(item => item.id !== id);
            this.expandedChartIds = this.expandedChartIds.filter(expId => expId !== id);
            this.$nextTick(() => {
              this.initChart();
            });
            this.$message.success('过程线删除成功');
          } else {
            this.$message.error(res.errorMessage);
          }
        });
      }).catch(() => {
      });
    },
    
    handlerestoreLine(id, index) {
      this.LineID = id;
      this.restoreList = this.chartDataList[index].data.lineInfos;
      this.restoreVisible = true;
    },
    
    handleCloseRefreshDel() {
      this.onGetLineInfo(() => {
        this.$message.success('删除点恢复成功');
      });
    },
    
    handleSetFilterData(data) {
      if (data) {
        this.filterSelectList = [...data];
        this.LineID = data[0].lineID;
        this.filterVisible = true;
      }
    },
    // 全选
    selectAll() {
      this.OUTLIERSIGNs = [0, 1, 2]
    },

    // 清空
    clearAll() {
      this.OUTLIERSIGNs = []
    },

    setQuickDate(type) {
      const today = new Date();
      const yesterday = new Date(today);
      yesterday.setDate(yesterday.getDate() - 1);
      
      const startOfWeek = new Date(today);
      startOfWeek.setDate(today.getDate() - today.getDay());
      
      const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);

      // 最近7天
      const sevenDaysAgo = new Date(today);
      sevenDaysAgo.setDate(today.getDate() - 6); 
      
      // 最近15天
      const fifteenDaysAgo = new Date(today);
      fifteenDaysAgo.setDate(today.getDate() - 14); 
      
      const formatDate = (date) => {
        return `${date.getFullYear()}/${String(date.getMonth() + 1).padStart(2, '0')}/${String(date.getDate()).padStart(2, '0')}`;
      };

      switch (type) {
        case 'today':
          this.timeData.dT1 = formatDate(today);
          this.timeData.dT2 = ''
          this.timeData.DtModeID = 4
          break;
        case 'yesterday':
          this.timeData.dT1 = formatDate(yesterday);
          this.timeData.dT2 = ''
          this.timeData.DtModeID = 4
          break;
        case 'week':
          this.timeData.dT1 = formatDate(startOfWeek);
          this.timeData.dT2 = formatDate(today);
          this.timeData.DtModeID = 3
          break;
        case 'month':
          this.timeData.dT1 = formatDate(startOfMonth);
          this.timeData.dT2 = formatDate(today);
          this.timeData.DtModeID = 3
          break;
        case '7days':
        this.timeData.dT1 = formatDate(sevenDaysAgo);
        this.timeData.dT2 = formatDate(today);
        this.timeData.DtModeID = 3
        break;
        case '15days':
        this.timeData.dT1 = formatDate(fifteenDaysAgo);
        this.timeData.dT2 = formatDate(today);
        this.timeData.DtModeID = 3
        break;
      }
    },
    changeTimeType(num){
        const _d = {...this.timeData}
        _d.DtModeID = num
        this.timeData = {..._d}
    }
  }
})
</script>

<style scoped lang="scss">
.chart-container {
 height: calc(100vh - 185px);
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  background: #fff;
  height: calc(100vh - 185px);
}

.chart-cards {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.chart-card {
  background: #fff;
  border-radius: 2px;
  transition: all 0.3s ease;
  overflow: hidden;
}

.chart-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  cursor: pointer;
  border-bottom: 1px solid #eaeaea;
  transition: background-color 0.2s;
  
  &:hover {
    background-color: #f9f9f9;
  }
}

.chart-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  
  .title-icon {
    margin-right: 8px;
    color: #409EFF;
    font-size: 18px;
  }
}

.chart-actions {
  .expand-icon {
    transition: transform 0.3s;
    
    &.expanded {
      transform: rotate(180deg);
    }
  }
}

.chart-card-content {
  padding: 0;
}

.chart-toolbar {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  background-color: #f9f9f9;
  border-bottom: 1px solid #eaeaea;
  flex-wrap: wrap;
  gap: 8px;
  
  .toolbar-btn {
    margin-right: 0;
  }
}

.chart-wrapper {
  margin: 0 auto;
  padding: 10px;
}

.chart-line {
  width:900px;
  height: 300px;
}

.chart-info {
  display: flex;
  padding: 12px 20px;
  background-color: #f9f9f9;
  border-top: 1px solid #eaeaea;
  font-size: 12px;
  
  .info-item {
    display: flex;
    margin-right: 24px;
    
    .info-label {
      color: #909399;
      margin-right: 6px;
    }
    
    .info-value {
      color: #606266;
      font-weight: 500;
    }
  }
}
.examine-filter-dialog .el-checkbox {
  height: auto;
}

.examine-filter-dialog .el-checkbox__input {
  margin-top: -1px;
}

.examine-filter-dialog .el-checkbox__label {
  font-size: 13px;
  padding-left: 6px;
}
.dialog-content {
  padding: 0 8px;
}
/* 筛选说明 */
.filter-tip {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background: #f0f7ff;
  border-radius: 4px;
  margin-bottom: 16px;
  font-size: 13px;
  color: #409EFF;
}

.filter-tip i {
  margin-right: 6px;
  font-size: 14px;
}

/* 筛选区域 */
.filter-section {
  margin-bottom: 16px;
}

.filter-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.filter-title {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.quick-actions {
  display: flex;
  align-items: center;
  gap: 4px;
}

.quick-actions .el-button {
  padding: 2px 6px;
  font-size: 12px;
  color: #409EFF;
}

.compact-option {
  margin-bottom: 8px;
  padding: 8px 12px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  transition: all 0.2s;
}

.compact-option:hover {
  border-color: #c0c4cc;
  background: #f5f7fa;
}

.compact-option:last-child {
  margin-bottom: 0;
}

.compact-checkbox {
  width: 100%;
  margin: 0;
}

.compact-checkbox >>> .el-checkbox__label {
  width: 100%;
  padding-left: 8px;
}

.option-content {
  display: flex;
  align-items: center;
  width: 100%;
}

.status-badge {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 8px;
  flex-shrink: 0;
}

.status-badge.pending {
  background: #909399;
}

.status-badge.approved {
  background: #67C23A;
}

.status-badge.rejected {
  background: #F56C6C;
}

.status-text {
  font-size: 13px;
  color: #303133;
  flex: 1;
}

.status-count {
  font-size: 12px;
  color: #909399;
  margin-left: 4px;
}
.filter-stats {
  display: flex;
  justify-content: space-between;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.stats-item {
  display: flex;
  align-items: center;
  gap: 6px;
}

.stats-label {
  font-size: 12px;
  color: #909399;
}

.stats-value {
  font-size: 12px;
  color: #303133;
  font-weight: 500;
}


/* 设置区域 */
.setting-section {
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.section-header i {
  color: #409EFF;
  margin-right: 6px;
  font-size: 14px;
}

.section-title {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

/* 时间类型选择 */
.type-radio-group {
  width: 100%;
  display: flex;
  flex-direction: row;
  gap: 8px;
}

.type-radio {
  width: 100%;
  margin: 0;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  transition: all 0.3s;
}

.type-radio:hover {
  border-color: #409EFF;
  background: #f0f7ff;
}

.is-checked {
  border-color: #409EFF;
  background: #f0f7ff;
}

.radio-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.radio-content i {
  font-size: 16px;
  color: #409EFF;
}

.radio-text {
  font-weight: 500;
  color: #303133;
  font-size: 13px;
}

.radio-desc {
  font-size: 12px;
  color: #909399;
  margin-left: auto;
}

/* 日期设置 */
.date-setting {
  margin-top: 8px;
}

.date-label {
  display: flex;
  align-items: center;
  margin-bottom: 6px;
  font-size: 13px;
  color: #606266;
}

.date-label i {
  margin-right: 4px;
  font-size: 12px;
  color: #409EFF;
}

.date-range-group {
  display: flex;
  gap: 12px;
}

.date-item {
  flex: 1;
}

.compact-date-picker {
  width: 100%;
}
/* 日期验证警告 */
.date-warning {
  display: flex;
  align-items: center;
  margin-top: 8px;
  padding: 6px 10px;
  background: #fef0f0;
  border: 1px solid #fbc4c4;
  border-radius: 4px;
  font-size: 12px;
  color: #f56c6c;
}

.date-warning i {
  margin-right: 4px;
}

</style>





